//
//  BirthdayViewController.swift
//  BirthdayManager
//
//  Created by Apple on 2020/12/23.
//  Copyright © 2020 Charles. All rights reserved.
//

import UIKit

class BirthdayViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    @IBOutlet weak var nameLabel: UITextField!
    @IBOutlet weak var birthdayLabel: UITextField!
    @IBOutlet weak var countLabel: UILabel!
    @IBOutlet weak var image: UIImageView!
    @IBOutlet weak var yearLabel: UILabel!
    @IBAction func tapPhoto(_ sender: Any) {
        let imagePicker = UIImagePickerController()
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            present(imagePicker, animated: true, completion: nil)
        }
    }
    
    var birthdayForEdit: birthday?
    override func viewDidLoad() {
        super.viewDidLoad()
        if let birthday = birthdayForEdit{
            nameLabel.text = birthday.name
            birthdayLabel.text = birthday.date
            countLabel.text = "距离ta的生日还有" +  birthday.count + "天"
            image.image = birthday.avatar
            yearLabel.text = "🐣ta已经" + birthday.year + "岁啦"
        }
        // Do any additional setup after loading the view.
    }
    
    
    @IBAction func camera(_ sender: Any) {
        let imagePicker = UIImagePickerController()
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            present(imagePicker, animated: true, completion: nil)
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
        self.image.image = selectedImage
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "save"{
            birthdayForEdit = birthday(name: nameLabel.text!,date: birthdayLabel.text!, count: "0", avatar: image.image)
        }
        
    }


}
